package com.tg.message.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.core.cloud.message.Message;
import com.tg.appcommon.android.ImageUtils;
import com.tg.data.helper.DeviceTypeStorage;
import com.tg.message.R;

import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder> {

    private Context mContext;
    private List<Message> mDatas;
    private boolean isEdit;
    private int pageStyle;
    private int currentPlayIndex = 0;

    public boolean isEdit() {
        return isEdit;
    }

    public void setEdit(boolean edit) {
        isEdit = edit;
    }

    private OnMessageItemListener onMessageItemListener;

    public void setOnMessageItemListener(OnMessageItemListener onMessageItemListener) {
        this.onMessageItemListener = onMessageItemListener;
    }

    public MessageAdapter(Context context, List<Message> datas) {
        this.mContext = context;
        this.mDatas = datas;
        pageStyle = 0;
    }

    @NonNull
    @Override
    public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_message_item, parent, false);
        return new MessageViewHolder(view);
    }

    private void loadImage(ImageView imageView, Message bean){
        if (bean == null || StringUtils.isEmpty(bean.getThumbnail())) {
            return;
        }
        String url = bean.getThumbnail();
        int rotation = DeviceTypeStorage.readDeviceRotation(mContext, bean.getDeviceId());
        RequestOptions requestOptions = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE).dontAnimate().placeholder(R.mipmap.message_img_defalut).error(R.mipmap.message_list_img_error);
        Glide.with(mContext).load(url).thumbnail(0.5f)
                .apply(requestOptions)
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        if (rotation == 0){
                            imageView.setImageDrawable(resource);
                        }else{
                            if (resource instanceof BitmapDrawable) {
                                Bitmap bitmap = ((BitmapDrawable) resource).getBitmap();
                                bitmap = ImageUtils.adjustPhotoRotation(bitmap, rotation);
                                if (rotation == 90 || rotation == 270) {
                                    bitmap = ImageUtils.ImageCropFromRotation(bitmap, false, 5, 3);
                                }
                                if(bitmap != null){
                                    imageView.setImageBitmap(bitmap);
                                }else{
                                    imageView.setImageDrawable(resource);
                                }
                            }else{
                                imageView.setImageDrawable(resource);
                            }
                        }
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {

                    }
                });
    }

    @SuppressLint("RecyclerView")
    @Override
    public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
        Message bean = mDatas.get(position);
        if (mContext == null) return;

        if (pageStyle == 1) {
            if (holder.innerRoot != null) {
                holder.innerRoot.setBackgroundResource((position == currentPlayIndex && !isEdit) ? R.drawable.real_white_rounded_bg : 0);
            }
        }

        RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) holder.root.getLayoutParams();
        lp.bottomMargin = position == mDatas.size() - 1 ? DimenUtil.dp2px(mContext, 10) : 0;
        holder.root.setLayoutParams(lp);

        if (StringUtils.isEmpty(bean.getThumbnail())) {
            holder.iv.setVisibility(View.GONE);
            holder.iv.setTag(com.module.appcommon.R.id.image_load_tag, "");
        } else {
            holder.iv.setVisibility(View.VISIBLE);
            loadImage(holder.iv, bean);
        }

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) holder.iv.getLayoutParams();
        layoutParams.rightMargin = DimenUtil.dp2px(mContext, 10);
        holder.iv.setLayoutParams(layoutParams);

        holder.timetv.setText(DateUtil.getMinStrToTime(bean.getStartTime()));
        holder.msgtv.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);

        // 消息名称
        if (!TextUtils.isEmpty(bean.getEvent().getCategoryName())) {
            holder.msgtv.setText(bean.getEvent().getCategoryName());
        } else if (!TextUtils.isEmpty(bean.getEvent().getMsg())) {
            holder.msgtv.setText(bean.getEvent().getMsg());
        } else {
            holder.msgtv.setText(R.string.message_event_unknown);
        }


        holder.msgtv.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        holder.itemView.setOnClickListener(v -> {
            if (onMessageItemListener != null) {
                onMessageItemListener.onClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDatas == null ? 0 : mDatas.size();
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    static class MessageViewHolder extends RecyclerView.ViewHolder {
        ImageView iv;
        TextView msgtv;
        TextView timetv;
        View root;
        View innerRoot;

        public MessageViewHolder(@NonNull View convertView) {
            super(convertView);
            root = convertView.findViewById(R.id.root);
            innerRoot = convertView.findViewById(R.id.inner_root);
            iv = convertView.findViewById(R.id.iv);
            msgtv = convertView.findViewById(R.id.msgtv);
            timetv = convertView.findViewById(R.id.timetv);
        }
    }


    public interface OnMessageItemListener {
        void onClick(int position);
    }
}
